package com.zhny.aiot.hfdj.picking.eggs.plugin;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhny.aiot.hfdj.picking.eggs.plugin.model.EggResponse;
import com.zhny.aiot.hfdj.picking.eggs.plugin.model.EggStoreEntry;
import com.zhny.aiot.plugin.ICenterFacilities;
import com.zhny.aiot.plugin.IDeviceFactory;
import com.zhny.aiot.plugin.core.utils.MessageUtils;
import com.zhny.aiot.plugin.model.DeviceEntity;
import com.zhny.aiot.plugin.model.MessageEntry;
import com.zhny.aiot.plugin.model.MessageType;
import com.zhny.aiot.plugin.model.TaskEntity;
import com.zhny.aiot.plugin.web.WebDevice;
import io.netty.util.internal.StringUtil;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.pf4j.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class    EggDevice extends WebDevice {
    private static final Logger log = LoggerFactory.getLogger(EggDevice.class);
    public EggDevice(IDeviceFactory factory, ICenterFacilities centerFacilities, DeviceEntity entity) {
        super (factory, centerFacilities, entity);
    }

    @Override
    protected void onRequestHttp(TaskEntity task, CloseableHttpClient httpClient) {
        log.info ("execute pick eggs api request!");
        URIBuilder uriBuilder =null;
        EggConfig config = (EggConfig)this.getConfig ();
        String date =new SimpleDateFormat("yyyy-MM-dd").format (new Date ());
        try {
            uriBuilder=new URIBuilder ("https://weichart.gxemp.com/Cainiaoapi/Solution/api.jsp");
            uriBuilder.addParameter("deviceId", config.getDeviceId ());
            uriBuilder.addParameter("password", config.getPassword ());
            uriBuilder.addParameter("day", date);
            HttpGet httpGet = new HttpGet (uriBuilder.build ());
            try (CloseableHttpResponse response =httpClient.execute (httpGet) ){
                String body = EntityUtils.toString (response.getEntity ());
                if(!StringUtils.isNullOrEmpty (body)){
                    List<EggResponse> eggResponseList = mapTo (body);
                    if(eggResponseList != null && eggResponseList.size () > 0)
                        successResponse(eggResponseList);
                }

            } catch (ClientProtocolException e) {
                throw new RuntimeException (e);
            } catch (ConnectTimeoutException e) {
                System.out.println("请求连接超时");
            } catch (IOException e) {
                throw new RuntimeException (e);
            }
        } catch (URISyntaxException e) {
            throw new RuntimeException (e);
        }
    }
    protected void successResponse(List<EggResponse> list) {
        log.info ("read pick eggs api response!");
        Map<String,List<EggResponse>> groupByResponseMap = list
                .stream ()
                .collect(Collectors.groupingBy(EggResponse::getDeviceTime));
        EggStoreEntry entry = new EggStoreEntry ();
        MessageEntry msg=MessageUtils.createMessageEntry (this.getId ());
        if(groupByResponseMap != null && groupByResponseMap.size () > 0) {
            Map.Entry<String,List<EggResponse>> map = groupByResponseMap.entrySet ().stream ().findFirst ().orElse (null);
            if(map != null) {
                setEggStoreEntry (map.getValue (), entry);
                msg.setType (MessageType.RESULT);
                msg.setData (entry);
                this.saveReal (entry);
                this.save (entry);
            }
        }else {
            msg.setType (MessageType.ERROR);
            msg.setData ("no exist pick eggs data !");
        }
        this.nofity (msg);
    }

    private void setEggStoreEntry(List<EggResponse> list,EggStoreEntry entry){
        for (EggResponse result: list){
            if(result.getLevelCode ().contains ("3S")){
                entry.setNum3S (result.getNum ());entry.setWeight3S (result.getWeight ());entry.setStore3S (result.getStore ());
            }
            if(result.getLevelCode ().contains ("2S")){
                entry.setNum2S (result.getNum ());entry.setWeight2S (result.getWeight ());entry.setStore2S (result.getStore ());
            }
            if(result.getLevelCode ().contains ("S")){
                entry.setNumS (result.getNum ());entry.setWeightS (result.getWeight ());entry.setStoreS (result.getStore ());
            }
            if(result.getLevelCode ().contains ("MS")){
                entry.setNumMS (result.getNum ());entry.setWeightMS (result.getWeight ());entry.setStoreMS (result.getStore ());
            }
            if(result.getLevelCode ().contains ("M")){
                entry.setNumM (result.getNum ());entry.setWeightM (result.getWeight ());entry.setStoreM (result.getStore ());
            }
            if(result.getLevelCode ().contains ("L")){
                entry.setNumL (result.getNum ());entry.setWeightL (result.getWeight ());entry.setStoreL (result.getStore ());
            }
            if(result.getLevelCode ().contains ("2L")){
                entry.setNum2L (result.getNum ());entry.setWeight2L (result.getWeight ());entry.setStore2L (result.getStore ());
            }
            if(result.getLevelCode ().contains ("3L")){
                entry.setNum3L (result.getNum ());entry.setWeight3L (result.getWeight ());entry.setStore3L(result.getStore ());
            }
            if(result.getLevelCode ().contains ("超小")){
                entry.setNumUltraSmall (result.getNum ());entry.setWeightUltraSmall (result.getWeight ());entry.setStoreUltraSmall(result.getStore ());
            }
            if(result.getLevelCode ().contains ("超大")){
                entry.setNumExtraLarge (result.getNum ());entry.setWeightExtraLarge (result.getWeight ());entry.setStoreExtraLarge (result.getStore ());
            }
            if(result.getLevelCode ().contains ("脏蛋")){
                entry.setNumDirtyEggs (result.getNum ());entry.setWeightDirtyEggs (result.getWeight ());entry.setStoreDirtyEggs (result.getStore ());
            }
            if(result.getLevelCode ().contains ("裂蛋")){
                entry.setNumCrackedEgg (result.getNum ());entry.setWeightCrackedEgg (result.getWeight ());entry.setStoreCrackedEgg (result.getStore ());
            }
            if(result.getLevelCode ().contains ("血蛋")){
                entry.setNumBloodEgg (result.getNum ());entry.setWeightBloodEgg (result.getWeight ());entry.setStoreBloodEgg (result.getStore ());
            }
            if(result.getLevelCode ().contains ("总量")){
                entry.setTotalNum (result.getNum ());entry.setTotalWeight (result.getWeight ());
            }
        }
    }

    private List<EggResponse> mapTo(String body){
        if(StringUtil.isNullOrEmpty (body))
            return null;
        ObjectMapper mapper=new ObjectMapper ();
        try {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            List<EggResponse> obj=mapper.readValue (body,new TypeReference<List<EggResponse>> () {});
            return obj;
//            return mapper.writeValueAsString(this);
        } catch (IOException e) {
            return null;
        }
    }
}
